package com.smcaiot.filesync.starter.handler.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import com.smcaiot.filesync.starter.handler.CompressHandler;
import com.smcaiot.filesync.starter.util.ImageUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * @Author: cz
 * @Date: 2023/6/28
 * @Description: 压缩图片处理类，需继承此类
 */
@Slf4j
public abstract class AbstractCompressPicHandler<T> extends BaseHandler<T> implements CompressHandler<T> {

    @Override
    public String process(String picPath) {
        Assert.notBlank(picPath, "图片地址不能为空");
        FileUtil.mkdir("/tmp/");
        String localPath = "/tmp/" + getNameByPath(picPath);
        fileHandler.download(picPath, localPath);
        String smallPicPath = compressImg(localPath);
        String remoteSmallPath = fileHandler.upload(smallPicPath,
                fileSyncProp.getBaseDir() + "/" + getNameByPath(smallPicPath), false);
        log.debug("上传缩略图地址：{}", remoteSmallPath);
        return remoteSmallPath;
    }

    protected String compressImg(String srcPath) {
        long maxSize = Optional.ofNullable(fileSyncProp.getCompress().getMaxSize()).orElse(50 * 1024L);
        double scale = Optional.ofNullable(fileSyncProp.getCompress().getScale()).orElse(0.8);
        try {
            String tmpPath = "/tmp/small_" + getNameByPath(srcPath);
            ImageUtil.compressImg(srcPath, maxSize, tmpPath, scale);
            return tmpPath;
        } catch (IOException e) {
            log.warn("压缩图片失败，地址: {}, 错误: {}", srcPath, e);
            return null;
        } finally {
            deleteFile(srcPath);
        }
    }

    private void deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }

}
